#!/usr/bin/python


import argparse
import clang.cindex
import io
import os
import sys
# import hashlib

if not sys.platform.startswith("win32"):
    from ctypes.util import find_library


def setup_clang(library):
    if library == None:
        # LibClang shared library default search paths
        if sys.platform.startswith("win32"):
            clang.cindex.Config.set_library_path("C:/Program Files/LLVM/bin")
        else:
            clang.cindex.Config.set_library_file(find_library('clang-18'))
            # clang.cindex.Config.set_library_path("/usr/lib")
    else:
        clang.cindex.Config.set_library_file(library)

def parse_any(cursor, classname, classmembers, baseclassname):
    for children in cursor.get_children():
        try:
            if children.kind == clang.cindex.CursorKind.CLASS_DECL:
                parse_classdecl(children, classname, classmembers, baseclassname)
            else:
                parse_any(children, classname, classmembers, baseclassname)
        except ValueError:
            pass


def parse_classdecl(cursor, classname, classmembers, baseclassname):
    if cursor.spelling == classname:
        for children in cursor.get_children():
            try:
                if children.kind == clang.cindex.CursorKind.FIELD_DECL:
                    parse_fielddecl(children, classname, classmembers)
                elif children.kind == clang.cindex.CursorKind.CXX_BASE_SPECIFIER:
                    base_class = children.get_definition()
                    for base_children in base_class.get_children():
                        if base_children.displayname == "cloneImpl(Ogre::HlmsDatablock *)" \
                                or base_children.displayname == "cloneImpl(HlmsDatablock *)":
                            baseclassname.append(base_class.spelling)
                            break
            except ValueError:
                pass


def parse_fielddecl(cursor, classname, classmembers):
    cursortype = cursor.type
    if cursortype.kind == clang.cindex.TypeKind.TYPEDEF:
        cursortype = cursortype.get_canonical()

    size = (-1, )
    if cursortype.kind == clang.cindex.TypeKind.RECORD:
        # LibClang detects FastArray<T> as RECORD (e.g. PbsBakedTextureArray)
        # @hack Consider RECORD as vector-like type
        size = (0, )
    elif cursortype.kind == clang.cindex.TypeKind.CONSTANTARRAY:
        if cursortype.element_type.kind == clang.cindex.TypeKind.CONSTANTARRAY:
            # Bidimensional C-style array
            # @todo Add support for multidimensional C-style array
            size = (cursortype.element_count,
                    cursortype.element_type.element_count)
        else:
            # C-style array
            size = (cursortype.element_count, )

    classmembers.append((cursor.spelling, size))


def writeFileIfChanged(newFile, fullPath):
    try:
        oldFile = io.open(fullPath, 'r', encoding='utf-8', newline="\n")
    except IOError:
        oldFile = None

    newFile.seek(0, io.SEEK_SET)

    oldData = oldFile.read() if oldFile else ''
    newData = newFile.read()

    # Raw compare.
    if oldData != newData:
        if oldFile:
            oldFile.seek(0, io.SEEK_SET)
        newFile.seek(0, io.SEEK_SET)
        print("File " + fullPath + " is outdated. Overwriting...")
        if oldFile:
            oldFile.close()
        oldFile = io.open(fullPath, 'w', encoding='utf-8', newline="\n")
        oldFile.write(newFile.read())
        oldFile.close()
    else:
        print("File " + fullPath + " is up to date.")
    newFile.close()
    return


def dump_cpp(dirname, basename, classname, classmembers, baseclassname):
    fullPath = dirname + "/" + basename
    newFile = io.StringIO(newline = "\n")

    dump_cpp_disclaimer( newFile )
    dump_cpp_license( newFile )
    
    dump_cpp_implementation( newFile, classname, classmembers, baseclassname )

    writeFileIfChanged(newFile, fullPath)
    

def dump_cpp_disclaimer(file):
    file.write(
u"""// This file has been auto-generated by {scriptname}
// Please DO NOT manually edit this file. Any subsequent invocation of {scriptname} will overwrite your modifications.

""".format(scriptname = os.path.basename(__file__))
    )


def dump_cpp_license(file):
    file.write(u"""/*
-----------------------------------------------------------------------------
This source file is part of OGRE-Next
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the \"Software\"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

"""
    )


def dump_cpp_implementation(file, classname, classmembers, baseclassname):
    file.write(
u"""namespace Ogre
{{
    //-----------------------------------------------------------------------------------
    void {classname}::cloneImpl( HlmsDatablock *datablock ) const
    {{
        {baseclassname}::cloneImpl( datablock );
        {classname} *datablockImpl = static_cast<{classname}*>( datablock );

""".format(baseclassname = baseclassname, classname = classname)
    )

    for classmember in classmembers:
        if (classmember[1][0] == -1):
            file.write(
u"""        datablockImpl->{membername} = {membername};
""".format(membername = classmember[0])
            )
        elif (classmember[1][0] == 0):
            file.write(
u"""
        for( size_t i=0; i<{membername}.size(); ++i )
        {{
            datablockImpl->{membername}.push_back( {membername}[i] );
        }}
""".format(membername = classmember[0])
            )
        else:
            file.write(
u"""
        for( size_t i=0; i<{membersize_0}; ++i )
        {{
""".format(membersize_0 = classmember[1][0])
            )

            if len(classmember[1]) == 1:
                if classmember[0] == "mSamplerblocks":
                    file.write(
u"""            datablockImpl->{membername}[i] = {membername}[i];
            if( datablockImpl->{membername}[i] )
                mCreator->getHlmsManager()->addReference( datablockImpl->{membername}[i] );
        }}
""".format(membername = classmember[0])
                    )
                else:
                    file.write(
u"""            datablockImpl->{membername}[i] = {membername}[i];
        }}
""".format(membername = classmember[0])
                    )
            else:
                file.write(
u"""            for( size_t j=0; j<{membersize_1}; ++j )
            {{
                datablockImpl->{membername}[i][j] = {membername}[i][j];
            }}
        }}
""".format(membername = classmember[0], membersize_1 = classmember[1][1])
                )

    file.write(
u"""    }
}
"""
    )




def main():
    argparser = argparse.ArgumentParser(description = "Auto-generate \"cloneImpl\" source code for HLMS datablock classes")
    argparser.add_argument("HEADER", nargs = "+", help = "HLMS datablock class header for which the \"cloneImpl\" source code has to be generated")
    argparser.add_argument("-I", "--include-directory", action = "append", help = "add directory to include search path")
    argparser.add_argument("-l", "--library", help = "set LibClang shared library (libclang.so or libclang.dll)")

    args = argparser.parse_args()

    setup_clang(args.library)

    index = clang.cindex.Index.create()
    indexargs = ["-x", "c++"]

    if args.include_directory:
        for includedirectory in args.include_directory:
            indexargs += ["-I", includedirectory]

    for header in args.HEADER:
        translationunit = index.parse(header, indexargs)
        translationunitdirname = os.path.dirname(translationunit.spelling)
        translationunitbasename = os.path.splitext(os.path.basename(translationunit.spelling))[0]

        classname = translationunitbasename.replace("Ogre", "")
        classmembers = []
        baseclassnames = []
        parse_any(translationunit.cursor, classname, classmembers, baseclassnames)

        # Sort classmembers for prettyprint source code
        classmembers.sort(key = lambda x: x[1][0])

        dump_cpp(translationunitdirname.replace("include", "src"), translationunitbasename + ".cpp.inc", classname, classmembers,baseclassnames[0])




if __name__ == "__main__":
    main()
